package cn.zn.framework.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.common.utils.MessageUtil;
import cn.zn.base.exception.CaptchaException;
import cn.zn.base.exception.CaptchaExpireException;
import cn.zn.base.exception.CustomException;
import cn.zn.base.exception.UserPasswordNotMatchException;
import cn.zn.base.factory.AsyncManager;
import cn.zn.framework.bean.LoginUser;
import cn.zn.framework.factory.OperateLogFactory;
import cn.zn.framework.service.JwtTokenService;
import cn.zn.framework.service.SysLoginService;
import cn.zn.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author zn-admin
 */
@Component
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private JwtTokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public Map<String, String> login(String username, String password) {
        // 登录验证
        return doLogin(username, password);
    }

    public Map<String, String> ssoLogin(String ssoToken) {
        String username = "";
        String password = "";

        if (StrUtil.isBlank(ssoToken)) {
            AsyncManager.instance().execute(OperateLogFactory.recordLogin(ssoToken, null, Constants.LOGIN_FAIL, "单点登录Token为空"));
            throw new CustomException("单点登录用户名为空");
        }
        String[] urlTokens = ssoToken.split("_");
        if (urlTokens.length != 2) {
            AsyncManager.instance().execute(OperateLogFactory.recordLogin(ssoToken, null, Constants.LOGIN_FAIL, "单点登录Token格式不正确"));
            throw new CustomException("单点登录Token格式不正确");
        }

        username = urlTokens[0];
        password = urlTokens[1];

        // 登录验证
        return doLogin(username + Constants.SSO_TYPE, password);
    }

    private Map<String, String> doLogin(String username, String password) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.instance().execute(OperateLogFactory.recordLogin(username, null, Constants.LOGIN_FAIL, MessageUtil.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.instance().execute(OperateLogFactory.recordLogin(username, null, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AsyncManager.instance().execute(OperateLogFactory.recordLogin(username, loginUser.getTheUser().getUserName(), Constants.LOGIN_SUCCESS, MessageUtil.message("user.login.success")));
        // 生成token
        String token = tokenService.createToken(loginUser);

        Map<String, String> result = new HashMap<>();
        result.put(Constants.TOKEN, token);
        return result;
    }
}
